// 实现这个项目的构建任务

const { src, dest, parallel, series, watch} = require('gulp')
const del = require('del')
const browerSync = require('browser-sync')
const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()
const bs = browerSync.create()

// 清除打包文件
const clean = () => {
    return del(['dist'])
}

//样式编译
const style = () => {
    return src('src/assets/styles/*.scss',{base: 'src'})
    .pipe(plugins.sass({ outputStyle: 'expanded'}))
    .pipe(dest('dist'))
}

//脚本编译
const script = () => {
    return src('src/assets/scripts/*.js',{base: 'src'})
    .pipe(plugins.babel({ presets:['@babel/preset-env']}))
    .pipe(dest('dist'))
}

// html模板编译
const page = () => {
    return src('src/*.html',{base: 'src'})
    .pipe(plugins.swig())
    .pipe(dest('dist'))
}

// 图片转换
const image = () => {
    return src('src/assets/images/**',{base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 字体转换
const font = () => {
    return src('src/assets/fonts/**',{base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 额外文件
const extra = () => {
    return src('public/**',{base: 'public'})
    .pipe(dest('dist'))
}

//开发服务器
const serve = () => {
    watch('src/assets/styles/*.scss',style)
    watch('src/assets/scripts/*.js',script)
    watch('src/*.html',page)
    // watch('src/assets/images/**',image)
    // watch('src/assets/fonts/**',font)
    // watch('public/**',extra)
    watch([
        'src/assets/images/**',
        'src/assets/fonts/**',
        'public/**'
    ], bs.reload)
    bs.init({
        notify:false,//消息提示
        port:2080,//端口
        // files:'dist/**',//监听变化-文件路径
        server:{
            baseDir:['dist', 'src', 'public'],
            routes:{
               '/node_modules': 'node_modules' 
            }
        }
    })
}

// 同步执行用parallel，顺序执行用series
const compile = parallel(style, script, page)

//上线之前执行的任务
const build = series(clean, parallel(compile, image, font, extra))

const develop = series(compile,serve)
module.exports = {
    compile,
    build,
    serve
}